import { call, put, takeLatest } from 'redux-saga/effects';

import api from '../../../api';

// import cityActionCreators from '../cityInfo/actionCreators';
import actionCreators from './actionCreators';
import { GET_VIEWPORT_SAGA } from './actionTypes';

/**
 * 地图位置信息获取，首先从缓存中获取，其次通过ip定位获取
 */
function* getLocation() {
    let viewport = localStorage.getItem('viewport');

    if (viewport) {
        viewport = JSON.parse(viewport);
        yield put(
            actionCreators.change({
                ...viewport,
                location: true,
            })
        );
        return;
    }

    console.log(call, api);
    let result = {
        statusInfo: {
            status: 500
        }
    }
    // const result = yield call(api.city.getLocation);
    // console.log(result, cityActionCreators);

    // yield put(
    //     actionCreators.change({
    //         center: [NaN, NaN],
    //         location: true,
    //     })
    // );

    if (result.statusInfo.status === 200) {
        if (result.lat && result.lng) {
            yield put(
                actionCreators.change({
                    center: [Number(result.lat), Number(result.lng)],
                    location: true,
                })
            );
        } else {
            yield put(
                actionCreators.change({
                    location: true,
                })
            )
        }
    } else {
        yield put(
            actionCreators.change({
                location: true,
            })
        );
    }
}

export default function* saga() {
    yield takeLatest(GET_VIEWPORT_SAGA, getLocation);
}
